package com.faner.fast.file.extension;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.faner.fast.file.AbstractUploader;
import com.faner.fast.file.FileConstant;
import com.faner.fast.file.FileProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;

/**
 * Oss文件上传
 * description: OssUploader
 * date: 2020/12/2 18:07
 * author: faner
 */
@Slf4j
public class OssUploader extends AbstractUploader {
    @Autowired
    private FileProperties fileProperties;

    @Value("${fast.file.oss.endpoint}")
    private String endpoint;

    @Value("${fast.file.oss.access-key}")
    private String accessKey;

    @Value("${fast.file.oss.secret-key}")
    private String secretKey;

    @Value("${fast.file.oss.bucket}")
    private String bucket;
    @Value("${fast.file.oss.dir}")
    private String dir;

    private OSSClient ossManage;

    @PostConstruct
    public void initUploadManager() {
        ossManage = new OSSClient(endpoint, accessKey, secretKey);
    }



    @Override
    protected FileProperties getFileProperties() {
        return fileProperties;
    }

    @Override
    protected boolean handleOneFile(byte[] bytes, String newFilename) {
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
        // 上传到阿里云
        try {
            PutObjectResult response = ossManage.putObject(bucket, dir+"/"+ newFilename, byteInputStream);
            log.info(response.toString());
        } catch (OSSException e) {
            String message = e.getMessage();
            log.error("oss upload file error: {}", message);
            return false;
        }
        return true;
    }

    @Override
    protected String getStorePath(String newFilename) {
//        return  fileProperties.getDomain() + "pdf/" + newFilename;
        return "http://"+ bucket +"."+ endpoint +"/" +dir+"/"+ newFilename;
    }

    @Override
    protected String getFileType() {
        return FileConstant.REMOTE;
    }
}
